<?php

namespace plugin\ycMassage\app\shop\controller;

use app\admin\validate\SystemAdmin;
use app\common\manager\PluginMgr;
use app\common\manager\SettingsMgr;
use app\common\manager\StoreAppMgr;
use app\common\service\SystemInfoService;
use app\common\service\UploadService;
use plugin\ycMassage\app\BaseController;
use app\common\utils\Password;
use plugin\ycMassage\app\model\MassageMch;
use plugin\ycMassage\app\model\MassageShop;
use plugin\ycMassage\app\model\MassageUser;
use plugin\ycMassage\utils\enum\Examine;
use plugin\ycMassage\utils\enum\State;
use plugin\ycMassage\utils\Str;
use support\Request;
use think\Exception;
use think\facade\Session;

/**
 * 公共控制器
 *
 * @author 贵州猿创科技有限公司
 * @Email 416716328@qq.com
 * @DateTime 2023-03-07
 */
class PublicsController extends BaseController
{
    protected $noNeedLogin = ['site', 'login'];
    protected $noNeedAuth = ['site', 'login', 'user', 'loginout', 'selectedUse'];
    public function site(Request $request)
    {
        $pluginVersion      = PluginMgr::getPluginVersionData($request->plugin);
        $systemInfo         = SystemInfoService::info();
        $project            = SettingsMgr::group($request->appid, 'system');
        if (!empty($project['web_logo'])) {
            $project['web_logo'] = UploadService::url($project['web_logo']);
        }
        if (empty($project['web_name'])) {
            $storeApp = StoreAppMgr::detail(['id' => $request->appid]);
            $project  = [
                'web_name'      => $storeApp['title'],
                'web_title'     => '门店管理',
                'web_logo'      => $storeApp['logo']
            ];
        }
        $pluginPrefix       = "app/{$request->plugin}";
        $domain = getHpConfig('domain', (int)$request->appid, 'plugins_domains');
        $data = [
            "web_name"                  => $project['web_name'],
            "web_title"                 => $project['web_title'] ?? "门店管理",
            "web_logo"                  => $project['web_logo'],
            'domain' => $domain,
            'web_url' => getHpConfig('web_url'),
            'plugin' => $this->request->plugin,
            "appid"                     => $request->appid,
            'version_name'              => $pluginVersion['version_name'],
            'version'                   => $pluginVersion['version'],
            # 版权token
            'empower_token'             => $systemInfo['site_encrypt'],
            # 版权私钥
            'empower_private_key'       => $systemInfo['privatekey'],
            # 登录页链接
            "public_api"                => [
                "login"                 => "{$pluginPrefix}/shop/Publics/login",
                "user"                  => "{$pluginPrefix}/shop/Publics/user",
                "loginout"              => "{$pluginPrefix}/shop/Publics/loginout",
                "clear"                 => "{$pluginPrefix}/shop/Index/clear",
                "lock"                  => "{$pluginPrefix}/shop/Index/lock",
                "user_edit"             => "{$pluginPrefix}/shop/User/editSelf",
                "header_right_file"     => "{$pluginPrefix}/remote/shop/header-toolbar",
            ],
            # 附件库
            "uploadify_api"             => [
                'index'                 => "{$pluginPrefix}/shop/Upload/index",
                'upload'                => "{$pluginPrefix}/shop/Upload/upload",
                'edit'                  => "{$pluginPrefix}/shop/Upload/edit",
                'del'                   => "{$pluginPrefix}/shop/Upload/del",
                'move'                  => "{$pluginPrefix}/shop/Upload/move",
            ],
            # 附件库分类
            'uploadify_cate' => [
                'index'                 => "{$pluginPrefix}/shop/UploadCate/index",
                'add'                   => "{$pluginPrefix}/shop/UploadCate/add",
                'edit'                  => "{$pluginPrefix}/shop/UploadCate/edit",
                'del'                   => "{$pluginPrefix}/shop/UploadCate/del",
            ],
        ];
        return $this->successRes($data);
    }

    /**
     * 应用登录
     * @param \support\Request $request
     * @return mixed
     * @author 贵州猿创科技有限公司
     * @copyright 贵州猿创科技有限公司
     * @email 416716328@qq.com
     */
    public function login(Request $request)
    {
        // 获取数据
        $post = $request->post();
        // 数据验证
        hpValidate(SystemAdmin::class, $post, 'login');

        // 查询数据
        $where = [
            'saas_appid'        => $request->appid,
            'mobile'            => $post['username']
        ];
        $UserModel = MassageUser::where($where)->find();
        if (!$UserModel) {
            return $this->fail('登录账号错误');
        }
        // 验证登录密码
        if (!Password::passwordVerify((string) $post['password'], (string)$UserModel->password)) {
            return $this->fail('登录密码错误');
        }
        if ($UserModel->state === State::NO['value']) {
            return $this->fail('该用户已被冻结');
        }
        Session::set($request->plugin . '_shop', $UserModel);

        // 更新登录信息
        $ip = $request->ip();
        $UserModel->last_login_ip = $ip;
        $UserModel->last_login_time = date('Y-m-d H:i:s');
        $UserModel->save();
        $MassageMch = MassageMch::where(['uid' => $UserModel->id, 'state' => State::YES['value'], 'examine' => Examine::YES['value']])->count();
        $MassageShop = MassageShop::where(['uid' => $UserModel->id, 'state' => State::YES['value'], 'examine' => Examine::YES['value']])->count();
        if ($MassageMch <= 0 && $MassageShop <= 0) {
            return $this->fail('您不是商户管理员');
        }

        // 返回数据
        return $this->successFul('登录成功', ['token' => Str::random(32)]);
    }

    /**
     * 用户信息
     * @param \support\Request $request
     * @return mixed
     * @author 贵州猿创科技有限公司
     * @copyright 贵州猿创科技有限公司
     * @email 416716328@qq.com
     */
    public function user(Request $request)
    {
        $where = [
            'saas_appid'    => $request->saas_appid,
            'id'            => $request->uid
        ];
        $MassageUser = MassageUser::where($where)->find();
        if (!$MassageUser) {
            throw new Exception('用户不存在');
        }
        MassageUser::checkWallet($MassageUser);
        if ($request->use_mch_id) {
            $MassageUser->use_mch_id = $request->use_mch_id;
        }
        if ($request->use_shop_id) {
            $MassageUser->use_shop_id = $request->use_shop_id;
        }
        Session::set($request->plugin . '_shop', $MassageUser);
        # 获取菜单数据
        $menus = PluginMgr::getMenus($request->plugin . '/app/shop');
        # 商户权限菜单
        if ($request->use_mch_id) {
            $shopMenu = PluginMgr::getOriginMenus($request->plugin . '/app/shop', 'shop.json');
            $shopMenus = PluginMgr::parseMenus($shopMenu);
            # 处理可展示数据
            foreach ($shopMenus as $key => $value) {
                $value['show'] = $value['show'] == '20' ? '1' : '0';
                $value['is_api'] = $value['is_api'] == '20' ? '1' : '0';
                $value['is_system'] = $value['is_system'] == '20' ? '1' : '0';
                $value['component'] = $value['component'] == 'none/index' ? '' : $value['component'];
                if (is_array($value['method'])) {
                    $value['method'] = current($value['method']);
                }
                $shopMenus[$key] = $value;
            }
            $menus = array_merge($menus, $shopMenus);
        }
        # 对菜单进行排序
        $menus = list_sort_by($menus, 'sort', 'asc');
        # 分配菜单数据
        $MassageUser->menus = $menus;
        if (!$MassageUser->username) {
            $MassageUser->username = $MassageUser->mobile;
        }
        $MassageMch = MassageMch::where(['uid' => $MassageUser->id, 'state' => State::YES['value'], 'examine' => Examine::YES['value']])
            ->field('id,title')->select();
        $mchs = [];
        foreach ($MassageMch as $item) {
            $mchs[] = [
                'id' => $item->id,
                'title' => $item->title
            ];
        }
        $MassageUser->mchs = $mchs;
        $MassageShop = MassageShop::where(['uid' => $MassageUser->id, 'state' => State::YES['value'], 'examine' => Examine::YES['value']])
            ->field('id,title')->select();
        $shops = [];
        foreach ($MassageShop as $item) {
            $shops[] = [
                'id' => $item->id,
                'title' => $item->title
            ];
        }
        $MassageUser->shops = $shops;
        $role=new \stdClass;
        $role->is_system='20';
        $MassageUser->role=$role;
        # 返回用户数据
        return $this->successRes($MassageUser);
    }

    /**
     * 退出登录
     * @param \support\Request $request
     * @return mixed
     * @author 贵州猿创科技有限公司
     * @copyright 贵州猿创科技有限公司
     * @email 416716328@qq.com
     */
    public function loginout(Request $request)
    {
        Session::delete($request->plugin . '_shop');
        return $this->success("退出成功");
    }
    public function selectedUse(Request $request)
    {
        $role = $request->post('role');
        $id = $request->post('id');
        if ((!$role || !$id) && ($request->use_mch_id || $request->use_shop_id)) {
            return $this->success('切换成功');
        }
        $where = [
            'saas_appid'    => $request->saas_appid,
            'id'            => $request->uid
        ];
        $MassageUser = MassageUser::where($where)->find();
        if ($role == 'mch') {
            $MassageMch = MassageMch::where(['uid' => $request->uid, 'id' => $id, 'state' => State::YES['value'], 'examine' => Examine::YES['value']])->find();
            if (!$MassageMch) {
                return $this->fail('商户不存在');
            }
            $MassageUser->use_mch_id = $MassageMch->id;
        } else {
            $MassageShop = MassageShop::where(['uid' => $request->uid, 'id' => $id, 'state' => State::YES['value'], 'examine' => Examine::YES['value']])->find();
            if (!$MassageShop) {
                return $this->fail('门店不存在');
            }
            $MassageUser->use_shop_id = $MassageShop->id;
        }
        Session::set($request->plugin . '_shop', $MassageUser);
        return $this->success('切换成功');
    }
}
